< previous page page_74 next page >

Page 74
Whether an item is selected is indicated by the list box's Selected property. Like the List property mentioned earlier, the Selected property is an array that has an element for each item in the list. The value of the Selected property for each item is either True (the item is selected) or False (the item is not selected).
You also need to know how many items are in the list so that you can set up the loop to check all the selections. This information is contained in the ListCount property. The following code prints onto the form the name of each list item that is selected:
numitm = Fruits.ListCount
For I = 0 to numitm - 1
   If Fruits.Selected(I) Then Form1.Print Fruits.List(I)
Next I
Keeping Other Data in the List
What if you want the users to see a meaningful list, such as a list of names, but you also want to have the list remember a number that's associated with each name? The ItemData property of a list box is, in essence, an array of long integers, one for each item that has been added to the list box. No matter what position an item occupies in the list box, the ItemData array remembers the number associated with that particular element. This happens even if the list box's Sorted property is True, meaning that items aren't necessarily listed in the order that they're added. For example, the ItemData array element associated with the first item in a list box named List1 can be accessed as List1.ItemData(0). The array element for the currently selected list box entry can be accessed with List1.ItemData(List1.ListIndex) (recall that the ListIndex property reports which item is currently selected).
As items are added to a list box, an associated element is created in the ItemData array. Of course, it's your job to place the appropriate value into the proper position of the ItemData array. So how can your program know into which list box position a newly added item went, especially if the list box is sorted? Visual Basic makes this task easy. A list box's NewIndex property contains the index number of the most recently added item in the list. The following code adds a new customer to a sorted list box and then adds that customer's account number to the correct element of the associated ItemData array:
    lstCustomers.AddItem "Thomas, June"
    lstCustomers.ItemData(lstCustomers.NewIndex) = 21472301
Now, your programs can allow the users to select from a list box containing meaningful elements (names), but the background processing can be done with an associated number, which is easier for the computer. This approach is illustrated in the following Click event procedure of the list box:
Private Sub lstCustomers_Click()
    Dim lgThisCust As Long
    lgThisCust = lstCustomers.ItemData(lstCustomers.ListIndex)
    Call LookUpAccount(lgThisCust)
End Sub

 
< previous page page_74 next page >